package com.nihome.entershopinfo.fragments;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nihome.entershopinfo.Constants;
import com.nihome.entershopinfo.R;
import com.nihome.entershopinfo.adapter.ExpandsLogAdapter;
import com.nihome.entershopinfo.application.SysApplication;
import com.nihome.entershopinfo.dialog.LoadingDialog;
import com.nihome.entershopinfo.entity.User;
import com.nihome.entershopinfo.entity.response.ExpandsLogRes;
import com.nihome.entershopinfo.entity.response.PageResponse;
import com.nihome.entershopinfo.entity.response.ResponseBase;
import com.nihome.entershopinfo.ui.HomePageActivity;
import com.nihome.entershopinfo.utils.DateFormatUtil;
import com.nihome.entershopinfo.utils.Log;
import com.nihome.entershopinfo.utils.RequestAPI;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;
import java.lang.reflect.Type;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Carson on 2017/7/24.
 */
public class ExpandsLogFragment extends Fragment implements View.OnClickListener{
    private static final String TAG = "ExpandsLogFragment";



    private static final int NUM = 20;    //设置条目数
    private int currentPage = 0;         //当前页
    private int countPage;               //总页数

    private Context mContext;
    private User mUser;
    private Gson mGson;
    private LoadingDialog dialog;

    private PullToRefreshListView expandsList;
    private ExpandsLogAdapter adapter;

    private List<ExpandsLogRes> expandsLogResList;


    private LinearLayout allLogLayout;
    private TextView allLogText;
    private View allLogLine;
    private LinearLayout singleShopLogLayout;
    private TextView singleShopLogText;
    private View singleShopLogLine;
    private LinearLayout chainShopLogLayout;
    private TextView chainShopLogText;
    private View chainShopLogLine;
    private TextView addChildShop;

    private int selectPosition = -1;


    private String findPartnerType = "0;1";


    private PullToRefreshBase.OnPullEventListener<ListView> onPullEventListener = new PullToRefreshBase.OnPullEventListener<ListView>() {
        @Override
        public void onPullEvent(PullToRefreshBase<ListView> refreshView, PullToRefreshBase.State state, PullToRefreshBase.Mode direction) {
            Log.d(TAG, "OnPullEvent:" + state.name());
            if (state.equals(PullToRefreshBase.State.PULL_TO_REFRESH)) {
                refreshView.getLoadingLayoutProxy(true, false).setPullLabel(getString(R.string.pull_to_refresh_pull_label));
                refreshView.getLoadingLayoutProxy(true, false).setReleaseLabel(getString(R.string.label_release_refresh));
                refreshView.getLoadingLayoutProxy(true, false).setRefreshingLabel(getString(R.string.label_refreshing));
                refreshView.getLoadingLayoutProxy(true, false).setLastUpdatedLabel(DateFormatUtil.getCurrentTime(System.currentTimeMillis()));
                if (currentPage + 1 < countPage) {
                    refreshView.getLoadingLayoutProxy(false, true).setPullLabel("加载数据中。。。");
                    refreshView.getLoadingLayoutProxy(false, true).setRefreshingLabel("加载数据中。。。");
                    refreshView.getLoadingLayoutProxy(false, true).setReleaseLabel("加载数据中。。。");
                } else {
                    refreshView.getLoadingLayoutProxy(false, true).setPullLabel("没有更多了");
                    refreshView.getLoadingLayoutProxy(false, true).setRefreshingLabel("没有更多了");
                    refreshView.getLoadingLayoutProxy(false, true).setReleaseLabel("没有更多了");
                }
            }
        }
    };

    private PullToRefreshBase.OnRefreshListener2 onRefreshListener = new PullToRefreshBase.OnRefreshListener2() {
        @Override
        public void onPullDownToRefresh(PullToRefreshBase refreshView) {
            //下拉刷新数据
            currentPage = 0;
            getExpandsLog();
        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase refreshView) {
            //加载数据
            new FinishRefresh().execute();
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mUser = SysApplication.getInstance().getmUser();
        mGson = new Gson();
        dialog = new LoadingDialog(mContext);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_expands_log, container, false);
        expandsList = (PullToRefreshListView) view.findViewById(R.id.expands_list);
        expandsList.setMode(PullToRefreshBase.Mode.BOTH);
        expandsList.setOnPullEventListener(onPullEventListener);
        expandsList.setOnRefreshListener(onRefreshListener);

        allLogLayout = (LinearLayout) view.findViewById(R.id.all_log_layout);
        allLogText = (TextView) view.findViewById(R.id.all_log_text);
        allLogLine = view.findViewById(R.id.all_log_line);
        singleShopLogLayout = (LinearLayout) view.findViewById(R.id.single_shop_log_layout);
        singleShopLogText = (TextView) view.findViewById(R.id.single_shop_log_text);
        singleShopLogLine = view.findViewById(R.id.single_shop_log_line);
        chainShopLogLayout = (LinearLayout) view.findViewById(R.id.chain_shop_log_layout);
        chainShopLogText = (TextView) view.findViewById(R.id.chain_shop_log_text);
        chainShopLogLine = view.findViewById(R.id.chain_shop_log_line);
        addChildShop = (TextView) view.findViewById(R.id.add_child_shop);

        allLogLayout.setOnClickListener(this);
        singleShopLogLayout.setOnClickListener(this);
        chainShopLogLayout.setOnClickListener(this);
        addChildShop.setOnClickListener(this);

        getExpandsLog();
        return view;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.all_log_layout:
                if (findPartnerType.equals("0;1")) return;
                currentPage = 0;
                findPartnerType = "0;1";
                getExpandsLog();
                allLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.red));
                singleShopLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.font_color));
                chainShopLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.font_color));
                allLogLine.setVisibility(View.VISIBLE);
                singleShopLogLine.setVisibility(View.INVISIBLE);
                chainShopLogLine.setVisibility(View.INVISIBLE);
                break;
            case R.id.single_shop_log_layout:
                if (findPartnerType.equals("0")) return;
                currentPage = 0;
                findPartnerType = "0";
                getExpandsLog();
                singleShopLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.red));
                allLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.font_color));
                chainShopLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.font_color));
                singleShopLogLine.setVisibility(View.VISIBLE);
                allLogLine.setVisibility(View.INVISIBLE);
                chainShopLogLine.setVisibility(View.INVISIBLE);
                break;
            case R.id.chain_shop_log_layout:
                if (findPartnerType.equals("1")) return;
                currentPage = 0;
                findPartnerType = "1";
                getExpandsLog();
                chainShopLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.red));
                allLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.font_color));
                singleShopLogText.setTextColor(ContextCompat.getColor(getActivity(), R.color.font_color));
                chainShopLogLine.setVisibility(View.VISIBLE);
                allLogLine.setVisibility(View.INVISIBLE);
                singleShopLogLine.setVisibility(View.INVISIBLE);
                break;
            case R.id.add_child_shop:
                if (selectPosition == -1) return;
                ExpandsLogRes log = expandsLogResList.get(selectPosition);
                /*if (log.getOtherInfoResponseDTO().getAuditStatus() == 101 || log.getOtherInfoResponseDTO().getAuditStatus() == 201
                        || log.getOtherInfoResponseDTO().getAuditStatus() == 202) {
                    Toast.makeText(mContext, "当前记录未审核通过", Toast.LENGTH_SHORT).show();
                    return;
                }*/
                if (log.getBasicInfoResponseDTO().getPartnerType() != 1) {
                    Toast.makeText(mContext, "当前记录不是连锁店信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                initShopData(1);
                break;
        }
    }

    private void initList(){
        if (adapter == null) {
            adapter = new ExpandsLogAdapter(mContext, expandsLogResList, mHandler);
            expandsList.setAdapter(adapter);
            expandsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    selectPosition = position - 1;
                    adapter.setSelectItem(selectPosition);
                    adapter.notifyDataSetChanged();
                }
            });
        }else {
            adapter.setData(expandsLogResList);
            adapter.notifyDataSetChanged();
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            currentPage = 0;
            getExpandsLog();
        }
    }

    private void getExpandsLog(){
        dialog.show(getString(R.string.load_text));
        String url = RequestAPI.EXPANDS_LOG_URL + "?marketerId="+mUser.getUserId()+"&page="+currentPage+"&size="+NUM +
                "&partnerTypes=" + findPartnerType;
        Log.e(TAG, url);
        OkHttpUtils.get().url(url).build().execute(new ExpandsLogCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                expandsList.onRefreshComplete();
                Log.e(TAG, e + "");
                dialog.dismiss();
                if (e instanceof UnknownHostException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof IOException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBase<PageResponse> response, int id) {
                expandsList.onRefreshComplete();
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        countPage = response.getResult().getTotalPage();
                        currentPage = response.getResult().getCurrentPage();
                        if (currentPage > 0) expandsLogResList.addAll(response.getResult().getAuditOtherInfoResponseDTOList());
                        else expandsLogResList = response.getResult().getAuditOtherInfoResponseDTOList();
                        initList();
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class ExpandsLogCallback extends Callback<ResponseBase<PageResponse>> {
        @Override
        public ResponseBase<PageResponse> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<PageResponse>>(){}.getType();
            ResponseBase<PageResponse> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }







    private void initShopData(int type){
        String url = RequestAPI.INIT_SHOP_DATA_URL + "?source="+ type +"&marketerId="+mUser.getUserId();
        OkHttpUtils.get().url(url).build().execute(new InitShopDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, e + "");
                if (e instanceof UnknownHostException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof IOException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBase<String> response, int id) {
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        SysApplication.getInstance().setAuditId(response.getResult());
                        ((HomePageActivity)getActivity()).xcxClick_chainChild(
                                expandsLogResList.get(selectPosition).getBasicInfoResponseDTO().getAuditId(), new ExpandsLogRes());
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class InitShopDataCallback extends Callback<ResponseBase<String>>{
        @Override
        public ResponseBase<String> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<String>>(){}.getType();
            ResponseBase<String> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }




















    private int position;
    public Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case ExpandsLogAdapter.LOOK:
                    position = message.arg1;
                    if (expandsLogResList.get(position).getBasicInfoResponseDTO().getPartnerType() == 1) {
                        short status = expandsLogResList.get(position).getOtherInfoResponseDTO().getAuditStatus();
                        if (status == 101 || status == 202) {
                            ((HomePageActivity)getActivity()).xcxClick_chain(expandsLogResList.get(position));
                        } else if (status == 201) {

                        } else {
                            ((HomePageActivity)getActivity()).childShopLogFragment(expandsLogResList.get(position));
                        }
                    } else {
                        ((HomePageActivity)getActivity()).lookDetailLog(expandsLogResList.get(position));
                    }
                    break;
                case ExpandsLogAdapter.VOUCHER:
                    position = message.arg1;
                    ((HomePageActivity)getActivity()).moneyVoucherBtn(expandsLogResList.get(position));
                    break;
            }
            return false;
        }
    });






    private class FinishRefresh extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result){
            if (currentPage + 1 >= countPage) {
                expandsList.onRefreshComplete();
                return;
            }
            currentPage ++;
            getExpandsLog();
        }
    }



}
